package controller;

import exception.OtherException;
import exception.RequestParameterErrorException;
import exception.SomeException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/3/11 14:16
 * Version:1.0-SNAPSHOT
 */
@Controller
@RequestMapping("/exception")
public class ExceptionController {

    // 当方法被@ExceptionHandler进行标注的时候
    // 表示当前方法专门用于处理异常
    // 该方法会处理当前Controller中遇到的异常
    // 其处理的异常类型根据当前注解的参数而定
    // 其参数是一个异常的class类型
    // 默认值为Exception.class
//    @ExceptionHandler(SomeException.class)
//    public ModelAndView exceptionHandler(Exception e){
//        ModelAndView mav = new ModelAndView();
//        mav.addObject("e",e);
//        mav.setViewName("exception");
//        return mav;
//    }
//
//    @ExceptionHandler(OtherException.class)
//    public ModelAndView exceptionHandler2(Exception e){
//        ModelAndView mav = new ModelAndView();
//        mav.addObject("e",e);
//        mav.setViewName("exception2");
//        return mav;
//    }

    @ExceptionHandler
    public ModelAndView exceptionHandler(Exception e){
        ModelAndView mav = new ModelAndView();
        mav.addObject("e",e);
        if(e instanceof SomeException){
            mav.setViewName("exception");
        } else if(e instanceof OtherException){
            mav.setViewName("exception2");
        } else{
            mav.setViewName("globalException");
        }
        return mav;
    }

    @RequestMapping("/f1")
    public void f1() throws SomeException {
        System.out.println("ExceptionController.f1");
        throw new SomeException("处理f1方法时遇到了异常");
    }

    @RequestMapping("/f2")
    public void f2() throws SomeException {
        throw new SomeException("处理f2方法时遇到了异常");
    }

    @RequestMapping("/f3")
    public void f3() throws OtherException {
        throw new OtherException("处理f3方法时遇到了异常");
    }

    @RequestMapping("/f4")
    public void f4() throws RequestParameterErrorException {
        throw new RequestParameterErrorException("处理f4方法时遇到了异常");
    }

}
